package service;

import entity.Score;
import entity.Student;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

//文件操作类 实现数据持久化
public class FileManager{
    private static final String STUDENT_FILE = "students.txt";
    private static final String SCORE_FILE = "scores.txt";
    private static final String BACKUP_DIR = "backup";

    //保存学生信息到文件
    public void saveStudent(Map<String,Student> studentMap){
        if(studentMap.isEmpty()){
            System.out.println("数据为空");
        }else {
            try (PrintWriter writer = new PrintWriter(new FileWriter(STUDENT_FILE))) {
                writer.println("学号,姓名,年龄,专业,入学时间");
                for (Student st : studentMap.values()) {
                    writer.printf("%s,%s,%d,%s,%s%n",
                            st.getStudentID(), st.getName(), st.getAge(), st.getMajor(), st.getEnrollDate());
                }
                System.out.println("数据保存成功");
            } catch (Exception e) {
                System.out.println("保存学生信息失败：" + e.getMessage());
            }
        }
    }

    //保存成绩信息到文件
    public void saveScore(Map<String,Score> scoreMap){
        if(scoreMap.isEmpty()){
            System.out.println("数据为空");
        }else {
            try (PrintWriter writer = new PrintWriter(new FileWriter(SCORE_FILE))) {
                writer.println("学号,语文成绩,数学成绩,英语成绩,总成绩");
                for (Score sc : scoreMap.values()) {
                    writer.printf("%s,%.1f,%.1f,%.1f,%.1f%n",
                            sc.getStudentId(), sc.getChinese(), sc.getMath(), sc.getEnglish(), sc.getTotalScore());
                }
                System.out.println("成绩保存成功");
            } catch (Exception e) {
                System.out.println("保存成绩信息失败：" + e.getMessage());
            }
        }
    }

    // 加载学生信息
    public  Map<String, Student> loadStudents() {
        Map<String, Student> map = new HashMap<>();
        File file = new File(STUDENT_FILE);
        if (!file.exists()) return map;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                String[] arr = line.split(",");
                if (arr.length == 5) {
                    String id = arr[0];
                    String name = arr[1];
                    int age = Integer.parseInt(arr[2]);
                    String major = arr[3];
                    LocalDate date = LocalDate.parse(arr[4]);
                    Student s = new Student(id, name, age, major, date);
                    map.put(id, s);
                }
            }
            System.out.println("数据加载成功");
        } catch (IOException e) {
            System.out.println("加载学生信息失败：" + e.getMessage());
        }
        return map;
    }

    //加载成绩信息
    public  Map<String, Score> loadScores() {
        Map<String, Score> map = new HashMap<>();
        File file = new File(SCORE_FILE);
        if (!file.exists()) return map;
        try(BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            reader.readLine(); //跳过表头
            while ((line = reader.readLine()) != null) {
                String[] arr = line.split(",");
                if (arr.length == 5) {
                    String id = arr[0];
                    double chinese=Double.parseDouble(arr[1]) ;
                    double math = Double.parseDouble(arr[2]);
                    double english = Double.parseDouble(arr[3]);
                    Score sc=new Score(id,chinese,math,english);
                    map.put(id, sc);
                }
            }
            System.out.println("数据加载成功");
        }catch (Exception e) {
            System.out.println("加载成绩信息失败：" + e.getMessage());
        }
      return map;
     }

     //备份数据
    public void saveBackup() {
        try{
            Files.createDirectories(Path.of(BACKUP_DIR));
            Files.copy(Paths.get(STUDENT_FILE), Paths.get(BACKUP_DIR, STUDENT_FILE), StandardCopyOption.REPLACE_EXISTING);
            Files.copy(Paths.get(SCORE_FILE), Paths.get(BACKUP_DIR, SCORE_FILE), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("数据备份成功。");
    }catch (IOException e) {
            System.out.println("备份失败：" + e.getMessage());
        }
    }
    }